//引入公共文件
import '@utils/init.js'

import ajax from '@utils/ajax.js'

//新增学生
$('#addStudentsBtn').click(async() => {

    const name = $('#addStudentsName').val();
    const age = $('#addStudentsAge').val();
    const gender = $('[name=addStudentsGender]:checked').val();
    const professionId = $('#studentProfession').val();
    const classesId = $('#studentClass').val();
    const imagesPath = $('#showImages').prop('src');
    const res = await ajax({
        url: '/students/createStudents',
        type: "POST",
        data: {
            name,
            age,
            gender,
            professionId,
            classesId,
            imagesPath
        },
    })
    if (res.code) {
        alert('学生新增成功')
        renderClassesSelect()
    }
})




//获取专业数据
import { getProfession, getProfessionClasses } from '@js/getData.js';
renderProfessionSelect();



export async function renderProfessionSelect() {
    const professionData = await getProfession();
    const professionHtml = professionData.result.map(item => `<option value="${item._id}">${item.name}</option> `).join('');
    $('#studentProfession').html(professionHtml);
    renderClassesSelect();
}

//获取班级数据渲染下拉框
export async function renderClassesSelect() {
    const professionId = $('#studentProfession').val();
    const classesData = await getProfessionClasses({ professionId });
    const classesHtml = classesData.map(item => `<option value="${item._id}">${item.name}</option> `).join('');
    $('#studentClass').html(classesHtml);
}
//点击专业切换班级
$('#studentProfession').change(function() {
    renderClassesSelect();
})

// 上传图片
uploadImages()
export function uploadImages() {
    $('#uploadImages').change(async function() {
        const files = this.files; //原生节点自带的方法files
        console.log(files);
        // 1. 创建表单对象
        const fd = new FormData();
        // 2. 将图片信息添加到表单对象中
        fd.append('file', files[0]);
        //因为封装的ajax有许多属性没有所以不能用封装的
        const res = await ajax({
            url: "/images/uploadImages",
            type: 'POST',
            data: fd,
            // 设置 jquery 不要对图片数据进行额外的处理
            contentType: false,
            processData: false,
            cache: false,

        })
        $('#showImages').prop('src', `http://localhost:3000/${res.result}`)

    })
}